<template>
  <h1>详情页</h1>
  <hr>
  <h1>{{weibo.nickname}}说了:{{weibo.content}}</h1>
  <p>发布于:{{weibo.created}}</p>
  <hr>
  <el-input v-model="comment.content" placeholder="请留下你的评论吧!"></el-input>
  <el-button type="primary" @click="post()" style="margin:10px">发布评论</el-button>
  <div v-for="c in arr">
    <h4>{{c.nickname}}评论说:{{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>
</template>

<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";

const weibo = ref({});
onMounted(()=>{
  //从url中获取到id
  let id = new URLSearchParams(location.search).get('id');

  loadComments(id);
  axios.get('http://localhost:8080/v1/weibos/'+id+'/detail')
      .then((res)=>{
        if (res.data.code==2002){
          weibo.value = res.data.data;
        }
      })
});

const comment =ref({content:''});
const post=()=>{
  //获取user数据
  let user = getUser();
  //如果没有获取到user数据,就让用户登录
  if (user==null){
    ElMessage.error('请先登录!');
    router.push('/login');
    return;
  };
  //给评论对象设置评论员id与微博id
  comment.value.userId =user.id;
  comment.value.weiboId =weibo.value.id;
  console.log(comment.value);
  let data = qs.stringify(comment.value);
  axios.post('http://localhost:8080/v1/comments/add-new',data)
      .then((res)=>{
        if (res.data.code==2002){
          ElMessage.success('评论成功!');
          loadComments(weibo.value.id);
        }
      })
};
//定义响应式变量arr保存评论数据
const arr = ref([]);
//定义加载评论的函数,参数是当前微博的id
const loadComments =(id)=>{
  //给后端发请求,查这条微博的评论
  axios.get('http://localhost:8080/v1/comments/'+id)
      .then((res)=>{
        if (res.data.code==2002){
          arr.value = res.data.data;
        }
      })
}


</script>


<style scoped>

</style>